<template>
  <div class="attendance-task-list">
    <el-card>
      <div slot="header">
        <span>签到任务列表</span>
      </div>

      <el-table
        :data="taskList"
        style="width: 100%"
        v-loading="loading">
        <el-table-column
          prop="title"
          label="任务标题"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="classroomName"
          label="班级"
          min-width="120">
        </el-table-column>
        <el-table-column
          label="签到类型"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="getTaskTypeTag(scope.row.type)">
              {{ getTaskTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="签到时间"
          min-width="240">
          <template slot-scope="scope">
            {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column
          label="签到率"
          min-width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="parseFloat(scope.row.signRate)"
              :format="percentageFormat">
            </el-progress>
          </template>
        </el-table-column>
        <el-table-column
          label="签到情况"
          min-width="120">
          <template slot-scope="scope">
            {{ scope.row.signedCount }}/{{ scope.row.totalCount }}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleViewDetails(scope.row)">查看详情</el-button>
            <el-button
              size="mini"
              type="success"
              @click="handleExport(scope.row)">导出数据</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 任务详情对话框 -->
    <el-dialog
      title="签到详情"
      :visible.sync="dialogVisible"
      width="70%">
      <div v-if="currentTask">
        <h3>{{ currentTask.title }}</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="班级">{{ currentTask.classroomName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentTask.createTime }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentTask.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentTask.endTime }}</el-descriptions-item>
          <el-descriptions-item label="签到类型">{{ getTaskTypeText(currentTask.type) }}</el-descriptions-item>
          <el-descriptions-item label="签到人数">{{ currentTask.signedCount }}/{{ currentTask.totalCount }}</el-descriptions-item>
          <el-descriptions-item label="签到率">{{ currentTask.signRate }}</el-descriptions-item>
        </el-descriptions>

        <!-- 签到码或二维码显示 -->
        <div v-if="currentTask.type === 4" style="margin: 20px 0; text-align: center;">
          <h4>签到码</h4>
          <el-tag type="success" style="font-size: 24px; padding: 10px 20px;">
            {{ getSignCode() }}
          </el-tag>
        </div>
        <div v-else-if="currentTask.type === 3" style="margin: 20px 0; text-align: center;">
          <h4>签到二维码</h4>
          <img :src="qrCodeUrl" style="width: 200px; height: 200px;" />
        </div>
        <div v-else-if="currentTask.type === 1" style="margin: 20px 0; text-align: center;">
          <h4>手势签到</h4>
          <div class="gesture-container">
            <div class="gesture-grid">
              <div v-for="i in 9"
                   :key="i"
                   class="gesture-point"
                   :class="{ 'active': isPointActive(i) }">
                {{ i }}
                <span v-if="getPointOrder(i)" class="point-order">{{ getPointOrder(i) }}</span>
              </div>
            </div>
            <div class="gesture-arrows">
              <div v-for="(arrow, index) in getGestureArrows()"
                   :key="index"
                   class="gesture-arrow"
                   :style="arrow.style">
                <i class="el-icon-arrow-right"></i>
                <span class="arrow-number">{{ index + 1 }}</span>
              </div>
            </div>
          </div>
          <div class="gesture-sequence" v-if="getGestureCode()">
            连接顺序：{{ formatGestureSequence() }}
          </div>
        </div>
        <div v-else-if="currentTask.type === 2" style="margin: 20px 0; text-align: center;">
          <h4>位置签到</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="经度">{{ getLocationInfo().longitude }}</el-descriptions-item>
            <el-descriptions-item label="纬度">{{ getLocationInfo().latitude }}</el-descriptions-item>
            <el-descriptions-item label="签到半径">{{ getLocationInfo().radius }}米</el-descriptions-item>
          </el-descriptions>
        </div>

        <h4 style="margin-top: 20px">已签到学生</h4>
        <el-table
          :data="currentTask.signedStudents"
          style="width: 100%">
          <el-table-column
            prop="name"
            label="学生姓名"
            width="120">
          </el-table-column>
          <el-table-column
            prop="signTime"
            label="签到时间"
            width="180">
          </el-table-column>
          <el-table-column
            label="操作"
            width="200">
            <template slot-scope="scope">
              <el-dropdown @command="(command) => handleSignCommand(command, scope.row)">
                <el-button type="primary" size="mini">
                  代签<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="sign">签到</el-dropdown-item>
                  <el-dropdown-item command="late">迟到</el-dropdown-item>
                  <el-dropdown-item command="absent">缺勤</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-tag :type="getRecordStatusType(scope.row.status)" style="margin-left: 10px">
                {{ getRecordStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <h4 style="margin-top: 20px">未签到学生</h4>
        <el-table
          :data="currentTask.unsignedStudents"
          style="width: 100%">
          <el-table-column
            prop="name"
            label="学生姓名"
            width="120">
          </el-table-column>
          <el-table-column
            label="操作"
            width="200">
            <template slot-scope="scope">
              <el-dropdown @command="(command) => handleSignCommand(command, scope.row)">
                <el-button type="primary" size="mini">
                  代签<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="sign">签到</el-dropdown-item>
                  <el-dropdown-item command="late">迟到</el-dropdown-item>
                  <el-dropdown-item command="absent">缺勤</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcode'

export default {
  name: 'AttendanceTaskList',
  data() {
    return {
      taskList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      currentTask: null,
      qrCodeUrl: ''
    }
  },
  created() {
    this.fetchTaskList()
  },
  methods: {
    async fetchTaskList() {
      this.loading = true
      try {
        const response = await this.$http.get('/api/teacher/attendance/tasks', {
          params: {
            current: this.currentPage,
            size: this.pageSize
          }
        })

        if (response.code === 1) {
          this.taskList = response.data.records
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '获取签到任务列表失败')
        }
      } catch (error) {
        console.error('获取签到任务列表失败:', error)
        this.$message.error('获取签到任务列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchTaskList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchTaskList()
    },
    async handleViewDetails(row) {
      try {
        const response = await this.$http.get(`/api/teacher/attendance/task/${row.id}/detail`)
        if (response.code === 1) {
          // 合并任务基本信息和详情数据
          this.currentTask = {
            ...row,
            ...response.data,
            totalCount: response.data.totalCount,
            signedCount: response.data.signedCount,
            signRate: response.data.signRate,
            type: row.type,
            content: row.content
          }
          this.dialogVisible = true
          if (this.currentTask.type === 3) {
            this.generateQRCode()
          }
        } else {
          this.$message.error(response.msg || '获取签到详情失败')
        }
      } catch (error) {
        console.error('获取签到详情失败:', error)
        this.$message.error('获取签到详情失败')
      }
    },
    getStatusType(status) {
      return status === 0 ? 'success' : 'info'
    },
    getStatusText(status) {
      return status === 0 ? '进行中' : '已结束'
    },
    getRecordStatusType(status) {
      switch (status) {
        case 1:
          return 'success'  // 出勤
        case 0:
          return 'warning'  // 迟到
        case 2:
          return 'danger'   // 缺勤
        default:
          return 'info'     // 其他状态
      }
    },
    getRecordStatusText(status) {
      switch (status) {
        case 1:
          return '出勤'
        case 0:
          return '迟到'
        case 2:
          return '缺勤'

      }
    },
    percentageFormat(percentage) {
      return percentage.toFixed(2) + '%'
    },
    async handleSignCommand(command, student) {
      try {
        const statusMap = {
          'sign': 1,  // 出勤
          'late': 0,  // 迟到
          'absent': 2 // 缺勤
        }

        const response = await this.$http.put('/api/teacher/attendance/status', {
          taskId: this.currentTask.id,
          studentId: student.id,
          status: statusMap[command]
        })

        if (response.code === 1) {
          this.$message.success('代签操作成功')
          // 重新获取详情
          await this.handleViewDetails(this.currentTask)
        } else {
          this.$message.error(response.msg || '代签操作失败')
        }
      } catch (error) {
        console.error('代签操作失败:', error)
        this.$message.error('代签操作失败')
      }
    },
    getSignCode() {
      try {
        const content = JSON.parse(this.currentTask.content)
        return content.code || ''
      } catch (e) {
        return ''
      }
    },
    getGestureCode() {
      try {
        const content = JSON.parse(this.currentTask.content)
        return content.gesture || ''
      } catch (e) {
        return this.currentTask.content || ''
      }
    },
    isPointActive(point) {
      const gesture = this.getGestureCode()
      return gesture.includes(point.toString())
    },
    getGestureArrows() {
      const gesture = this.getGestureCode()
      const arrows = []

      for (let i = 0; i < gesture.length - 1; i++) {
        const from = parseInt(gesture[i])
        const to = parseInt(gesture[i + 1])

        // 计算起点和终点的位置
        const fromRow = Math.floor((from - 1) / 3)
        const fromCol = (from - 1) % 3
        const toRow = Math.floor((to - 1) / 3)
        const toCol = (to - 1) % 3

        // 计算箭头的位置和旋转角度
        const fromX = fromCol * 70 + 40
        const fromY = fromRow * 70 + 40
        const toX = toCol * 70 + 40
        const toY = toRow * 70 + 40

        const angle = Math.atan2(toY - fromY, toX - fromX) * 180 / Math.PI
        const length = Math.sqrt(Math.pow(toX - fromX, 2) + Math.pow(toY - fromY, 2))

        arrows.push({
          style: {
            left: `${fromX}px`,
            top: `${fromY}px`,
            width: `${length}px`,
            transform: `rotate(${angle}deg)`
          }
        })
      }

      return arrows
    },
    getLocationInfo() {
      try {
        const content = JSON.parse(this.currentTask.content)
        return {
          longitude: content.longitude || 0,
          latitude: content.latitude || 0,
          radius: content.radius || 0
        }
      } catch (e) {
        return {
          longitude: 0,
          latitude: 0,
          radius: 0
        }
      }
    },
    async generateQRCode() {
      try {
        const content = JSON.parse(this.currentTask.content)
        const qrData = content.qrCode || ''
        this.qrCodeUrl = await QRCode.toDataURL(qrData, {
          width: 200,
          margin: 1
        })
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.$message.error('生成二维码失败')
      }
    },
    getTaskTypeText(type) {
      const typeMap = {
        0: '普通签到',
        1: '手势签到',
        2: '位置签到',
        3: '二维码签到',
        4: '签到码签到'
      }
      return typeMap[type] || '未知类型'
    },
    getTaskTypeTag(type) {
      const typeMap = {
        0: '',
        1: 'info',
        2: 'warning',
        3: 'success',
        4: 'primary'
      }
      return typeMap[type] || ''
    },
    getPointOrder(point) {
      const gesture = this.getGestureCode()
      const index = gesture.indexOf(point.toString())
      return index !== -1 ? index + 1 : null
    },
    formatGestureSequence() {
      const gesture = this.getGestureCode()
      return gesture.split('').join(' → ')
    },
    async handleExport(row) {
      try {
        const token = localStorage.getItem('token')
        // 使用 XMLHttpRequest 发送带有 token 的请求
        const xhr = new XMLHttpRequest()
        xhr.open('GET', `http://localhost:8080/api/teacher/attendance/task/${row.id}/export`, true)
        xhr.setRequestHeader('Authorization', token)
        xhr.responseType = 'blob'

        xhr.onload = function() {
          if (xhr.status === 200) {
            // 创建 blob 链接并下载
            const blob = new Blob([xhr.response], { type: 'application/vnd.ms-excel' })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = `签到数据_${row.title}_${new Date().getTime()}.xlsx`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          } else {
            this.$message.error('导出数据失败')
          }
        }

        xhr.onerror = () => {
          this.$message.error('导出数据失败')
        }

        xhr.send()
      } catch (error) {
        console.error('导出数据失败:', error)
        this.$message.error('导出数据失败')
      }
    }
  }
}
</script>

<style scoped>
.attendance-task-list {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-descriptions {
  margin: 20px 0;
}

.gesture-container {
  display: inline-block;
  position: relative;
  margin: 20px 0;
}

.gesture-grid {
  display: grid;
  grid-template-columns: repeat(3, 60px);
  grid-template-rows: repeat(3, 60px);
  gap: 10px;
  background: #f5f7fa;
  padding: 10px;
  border-radius: 8px;
}

.gesture-point {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  font-size: 20px;
  font-weight: bold;
  color: #606266;
  transition: all 0.3s;
  position: relative;
}

.point-order {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #67c23a;
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.gesture-point.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.gesture-arrows {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.gesture-arrow {
  position: absolute;
  color: #409eff;
  font-size: 24px;
  transform-origin: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow-number {
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  background: #67c23a;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
}

.gesture-sequence {
  margin-top: 20px;
  font-size: 16px;
  color: #606266;
}
</style>
